-- UISkyCityTeam
-- Create by chendh
-- 天空之城编组列表界面

-- UISkyCityTeam继承自Layer
UISkyCityTeam = class("UISkyCityTeam", function()
    return cc.Layer:create();
end);

function UISkyCityTeam.create(campId)
    return UISkyCityTeam.new(campId);
end

-- 最大行数
local PAGE_ROW     = 4;
local MAX_COLUMN   = 4;

local groupPetList   = {};
local groupRobotList   = {};

-- 内部函数声明

-- 构造函数
function UISkyCityTeam:ctor(campId)
    -- 初始化
    self:setName("UISkyCityTeam");
    local node = cc.CSLoader:createNode("layout/sky_city/SkyCityTeam.csb");
    self:addChild(node);
    self.node = node;
    self.campId = campId;

    local CT = node:getChildByName("CT");
    local template = CT:getChildByName("template");
    local scrollview = template:getChildByName("scroll_view");
    self.CT = CT;
    self.scrollView = scrollview;
    self.scrollView:setVisible(true);

    -- 垂直滑动，需要显示上下蒙版
    local mask1 = findChildByName(self.node, "CT/template/mask1");
    mask1:setVisible(true);
    local mask2 = findChildByName(self.node, "CT/template/mask2");
    mask2:setVisible(true);

    -- 调整下标题背景图片资源
    local bgTypeImg1 = findChildByName(self.node, "CT/template/bg_type");
    local bgTypeImg2 = findChildByName(self.node, "CT/template/bg_type2");
    bgTypeImg2:setVisible(true);
    bgTypeImg1:loadTexture(getTitleBgIconPath("airship"));
    bgTypeImg2:loadTexture(getTitleBgIconPath("airship"));

    -- 修改滚动方向
    -- 1 垂直
    -- 2 水平
    self.scrollView:setDirection(1);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化列表数据
    self:initData();

    -- 初始化格子
    self:initGrids(self.node);

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UISkyCityTeam:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 获取分组中冈布奥列表
function UISkyCityTeam:getGroupPetList()
    return groupPetList;
end

-- 获取分组中机器人列表
function UISkyCityTeam:getGroupRobotList()
    return groupRobotList;
end

-- 初始化飞船列表数据
function UISkyCityTeam:initData()
    -- 出战的冈布奥
    groupPetList = SkyCombatM.getGroup(self.campId);

    -- 出战的机器人
    local robotGroup = SkyRobotM.getRobotsByCamp(self.campId);

    groupRobotList = {};
    for robotId, num in pairs(robotGroup) do
        for i = 1, num do
            table.insert(groupRobotList, robotId);
        end
    end

    -- 对宠物进行排序
    self:sortData();

    printTable(groupPetList, "groupPetList = ");
    printTable(groupRobotList, "groupRobotList = ");
end

-- 排序
function UISkyCityTeam:sortData()
    -- 排序冈布奥
    local petList = groupPetList;

    local function sortPet(id1, id2)
        local pet1 =  ME.user.pets[id1];
        local pet2 =  ME.user.pets[id2];
        local petAbility1 = FormulaM.invoke("CALC_SINGLE_PET_ABILITY", pet1);
        local petAbility2 = FormulaM.invoke("CALC_SINGLE_PET_ABILITY", pet2);

        if petAbility1 == petAbility2 then
            local list1 = SkyShipSkillM.getShipSkillsByPetId(id1);
            local list2 = SkyShipSkillM.getShipSkillsByPetId(id2);
            local activeNum1 = 0;
            local activeNum2 = 0;

            for _, info in ipairs(list1) do
                if SkyShipSkillM.isSkillActived(info["id"], petList) then
                    activeNum1 = activeNum1 + 1;
                end
            end
            for _, info in ipairs(list2) do
                if SkyShipSkillM.isSkillActived(info["id"], petList) then
                    activeNum2 = activeNum2 + 1;
                end
            end

            if #list1 == #list2 then
                if activeNum1 == activeNum2 then
                    return id1 > id2;
                else
                    return activeNum1 > activeNum2;
                end
            else
                return #list1 > #list2;
            end
        else
            return petAbility1 > petAbility2;
        end
    end

    if #petList > 0 then
        table.sort(petList, sortPet);
    end

    -- 排序机器人
    local robotList = groupRobotList;

    local function sortRobot(id1, id2)
        return SkyRobotM.query(id1, "fight_ability") > SkyRobotM.query(id2, "fight_ability");
    end
    if #robotList > 0 then
        table.sort(robotList, sortRobot);
    end
end

-- 初始化格子
function UISkyCityTeam:initGrids(node)
    local w = DESIGN_WIDTH;
    local h = DESIGN_HEIGHT;

    -- 图标间距(横向)
    local wGap = 1;

    -- 图标间距(纵向)
    local hGap = 10;

    -- 图标宽度
    local iconWidth = 127;

    -- 图片高度
    local iconHeight = 110;

    local topHGap  = 15;
    local bottomHGap  = 50;
    local leftWGap = 10;

    -- 总数
    local totalCount = SkyCombatM.getMaxPetNum();

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/sky_city/SkyCityPetItem.csb");
    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsVertical(self, self.scrollView, itemNode, totalCount, PAGE_ROW, MAX_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, bottomHGap, leftWGap, self.registerPetItemTouchEvent);

    for _, child in ipairs(self.scrollView.rows) do
        child:setScale(0.88);
    end
end

-- 显示英雄选择界面
function UISkyCityTeam:redraw()
    local curPetNum = #groupPetList + #groupRobotList;
    local totalCount = SkyCombatM.getMaxPetNum();

    -- 显示标题
    local titleLabel = findChildByName(self.node, "CT/template/title");
    local petNumLabel = findChildByName(self.node, "CT/pet_name");
    TextStyleM.setTitleStyle(titleLabel);
    TextStyleM.setTextStyle(petNumLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -2);
    TextStyleM.setShadowStyle(petNumLabel, cc.size(0, -3));
    TextStyleM.setOutlineStyle(petNumLabel, 1.5, TextStyleM.TEXT_OUTLINE_COLOR, true);

    local titleText = CampM.query(self.campId, "name");

    -- 显示出战数量及可出战数量
    petNumLabel:setVisible(true);
    local subText = string.format(getLocStr("number_proportion"), curPetNum, totalCount);

    -- 自动调整下位置
    adjustTitlePos(titleLabel, petNumLabel, 0, titleText, subText);

    -- 绘制信息
    -- 显示信息
    for i = 1, totalCount do
        local grid = self.scrollView:getChildByName("item" .. i);
        if grid then
            --  初始化格子信息
            self:initGridInfo(grid, i);
        end
    end

    if self.lastTotalNum then
        local grid = self.scrollView:getChildByName("item" .. self.lastTotalNum + 1);
        if grid then
            local addIcon = grid:getChildByName("add");
            addIcon:setVisible(false);
            addIcon:stopAllActions();
        end
    end
    self.lastTotalNum = #groupPetList + #groupRobotList;
    local grid = self.scrollView:getChildByName("item" .. self.lastTotalNum + 1);
    if grid then
        local addIcon = grid:getChildByName("add");
        addIcon:setVisible(true);

        -- 呼吸效果
        playBubbleAnima(addIcon, false);
    end

    -- 翻页按钮
    local btnLast = findChildByName(self.node, "CT/btn_last");
    local btnNext = findChildByName(self.node, "CT/btn_next");
    btnLast:setVisible(false);
    btnNext:setVisible(false);
end

--  初始化格子信息
function UISkyCityTeam:initGridInfo(grid, index)
    local bgImg = grid:getChildByName("bg");
    local grayBgImg = grid:getChildByName("gray_bg");
    local focusImg = grid:getChildByName("focus");
    local iconImg = grid:getChildByName("icon");
    local descLable = grid:getChildByName("desc");
    local skillNode = grid:getChildByName("skill");

    focusImg:setVisible(false);

    if index > 0 and index <= #groupPetList then
        bgImg:setVisible(true);
        grayBgImg:setVisible(false);
        iconImg:setVisible(true);

        -- 冈布奥使用普通的框
        bgImg:loadTexture(getFrameBgIconPath("normal"));

        local petId = groupPetList[index];
        -- 冈布奥图标
		local pet = PetM.getMyPet(petId);
        local iconIndex = pet:getIcon();
        iconImg:loadTexture(getHeroIconPath(iconIndex));
        descLable:setVisible(true);

        -- 冈布奥的战力
        local pet =  ME.user.pets[petId];
        local petAbility = FormulaM.invoke("CALC_SINGLE_PET_ABILITY", pet)
        TextStyleM.setTextStyle(descLable, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -3);
        descLable:setString(petAbility);

        -- 绘制冈布奥当前的秘宝信息
        local petSkillList = SkyShipSkillM.getShipSkillsByPetId(petId);
        local activeSkillList = {};

        for _, info in ipairs(petSkillList) do
            if SkyShipSkillM.isSkillActived(info["id"], groupPetList) then
                table.insert(activeSkillList, info["id"]);
            end
        end

        skillNode:removeAllChildren();
        local lightStarPath = "images/ui/symbol/point_01.png";
        local darkStarPath = "images/ui/symbol/point_02.png";
        local sinkerLayer = createStarLayerEx(#activeSkillList, #petSkillList, lightStarPath, darkStarPath, "right", -0.25);
        sinkerLayer:setScale(1.2 * sinkerLayer:getScale());
        sinkerLayer:setScaleX(-1 * sinkerLayer:getScaleX());
        skillNode:addChild(sinkerLayer);
        skillNode:setVisible(true);
    elseif index > #groupPetList and index <= #groupPetList + #groupRobotList then
        -- 机器人
        bgImg:setVisible(true);
        grayBgImg:setVisible(false);
        iconImg:setVisible(true);
        skillNode:setVisible(false);

        -- 机器人使用和秘宝一样的框
        bgImg:loadTexture(getFrameBgIconPath("airship_skill"));

        local robatId = groupRobotList[index - #groupPetList];
        -- 机器人图标
        local iconIndex = SkyRobotM.query(robatId, "icon");
        iconImg:loadTexture(getRobotIconPath(iconIndex));
        descLable:setVisible(true);

        -- 机器人的战力
        TextStyleM.setTextStyle(descLable, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_LIGHT_BLUE, true, -3);
        descLable:setString(SkyRobotM.query(robatId, "fight_ability"));
    else
        bgImg:setVisible(false);
        grayBgImg:setVisible(true);
        iconImg:setVisible(false);
        descLable:setVisible(false);
        skillNode:setVisible(false);
    end
end

-- 注册飞艇点击事件
function UISkyCityTeam:registerPetItemTouchEvent(node)
    -- 打开详情界面
    local function showPetInfo(index)
        self.isLongPress = true;

        local petId;
        local targetType = "pet";
        if index <= #groupPetList then
            petId = groupPetList[index];
        else
            targetType = "robot";
            petId = groupRobotList[index - #groupPetList];
        end

        if index > 0 and index <= #groupPetList + #groupRobotList then
            require "game/ui/form/sky_city/UISkyCityPetInfo"
            -- 打开冈布奥详细信息界面
            local uiForm = UISkyCityPetInfo.create(petId, self.campId, targetType, index, "replace");
            UIMgr.getCurrentScene():addForm(uiForm);

            self:setVisible(false);
        else
            require "game/ui/form/sky_city/UISkyCityPetList"

            -- 打开冈布奥列表界面
            local uiForm = UISkyCityPetList.create(self.campId);
            UIMgr.getCurrentScene():addForm(uiForm);

            self:setVisible(false);
        end

        AudioM.playFx("ui_open1");
    end

    -- 注册商品图标点击事件
    local bgImg = node:getChildByName("bg");
    local grayBgImg = node:getChildByName("gray_bg");
    local function onClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            showPetInfo(node.index);
        end
    end
    bgImg:addTouchEventListener(onClick);
    grayBgImg:addTouchEventListener(onClick);
end

-- 注册事件处理回调函数
function UISkyCityTeam:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UISkyCityTeam");
        elseif eventType == "enter" then

        end
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UISkyCityTeam", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UISkyCityTeam" then
            local btNode = findChildByName(self.node, "BT");
            btNode:setVisible(true);

            self:setVisible(true);
        elseif para["lose"] == "UISkyCityTeam" then
            local btNode = findChildByName(self.node, "BT");
            btNode:setVisible(false);
        end
    end);

    -- 编组发生变化的回调
    EventMgr.register("UISkyCityTeam", event.SKY_CITY_SAVE_GROUP, function(para)
        self:initData();
        self:redraw();

        -- 出战特效
        self:playActivedEffect(para["actived"], para["activedType"]);
    end);
end

-- 播放出战特效
function UISkyCityTeam:playActivedEffect(actived, activedType)
    if not actived or not activedType then
        return;
    end

    -- 找到出战的冈布奥，滚动过去，选中它
    local index;
    local iconIndex;
    local iconPath;
    if activedType == "pet" then
        index = table.indexOf(groupPetList, actived);
        iconIndex = PetM.getDefaultIcon(actived);
        iconPath = getHeroIconPath(iconIndex);
    else
        index = #groupPetList + table.indexOf(groupRobotList, actived);
        iconIndex = SkyRobotM.query(actived, "icon");
        iconPath = getRobotIconPath(iconIndex);
    end
    local petGrid = self.scrollView:getChildByName("item" .. index);
    local petIcon = petGrid:getChildByName("icon");
    petIcon:setVisible(false);

    -- 计算内部容器位移
    local hGap = 10;
    local topHGap  = 5;
    local iconHeight = 110;
    local viewHeight = self.scrollView:getContentSize().height;
    local innerHeight = self.scrollView:getInnerContainerSize().height;
    local y = innerHeight - topHGap - (math.floor(index / MAX_COLUMN) - 1) * (iconHeight + hGap) - iconHeight / 2;

    local max = innerHeight - viewHeight / 2;
    local min = viewHeight / 2;
    if y > max then
        y = max;
    end
    if y < min then
        y = min;
    end

    -- 滚动内部容器
    local moveTo = cc.MoveTo:create(0.1, cc.p(0, viewHeight / 2 - y));
    self.scrollView:getInnerContainer():runAction(moveTo);

    -- 新增冈布奥icon淡入并掉入格子，显示格子中的冈布奥图标，icon放大并淡出
    local icon = ccui.ImageView:create();
    icon:loadTexture(iconPath);
    icon:setOpacity(0);
    icon:setPosition(petIcon:getPositionX(), petIcon:getPositionY() + 100);
    petGrid:addChild(icon);

    local fadeIn = cc.FadeIn:create(0.3);
    local moveTo = cc.EaseIn:create(cc.MoveBy:create(0.3, cc.p(0, -100)), 2.5);
    local scale = petIcon:getScale();
    local scaleTo = cc.ScaleTo:create(0.5, scale * 2);
    local callFunc = cc.CallFunc:create(function()
        petGrid:removeChild(icon);
    end);
    local showPet = cc.CallFunc:create(function()
        petIcon:setVisible(true);
    end);

    AudioM.playFx("slime_play");
    icon:runAction(cc.Sequence:create(cc.Spawn:create(fadeIn, moveTo), showPet, cc.Spawn:create(scaleTo, cc.FadeOut:create(0.5)), callFunc));
end

-- 注册点击事件
function UISkyCityTeam:registerTouchEvent()
    -- 注册确定按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("ship_click");
            UIMgr.getCurrentScene():removeFormByName("UISkyCityTeam");
        end
    end
    AddBackEventHandler(self, btnBack, onOkClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_ok"));

    -- 注册说明碎片按钮点击事件
    local btnExchange = findChildByName(self.node, "BT/btn_info");
    local function onExchangeClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 打开说明界面
            require "game/ui/form/sky_city/UIAirShipSkillExplain"
            UIMgr.getCurrentScene():removeFormByName("UIAirShipSkillExplain");

            local title = string.format(getLocStr("sky_city_team_desc_title"), CampM.query(self.campId, "name"));
            local msg = string.format(getLocStr("sky_city_team_desc_msg"), SkyCombatM.getMaxPetNum());
            local function callback()
                -- 打开抽奖界面
                require "game/ui/form/shop/UIPetRecruit"
                local uiPetRecruit = UIPetRecruit.create(self.campId);
                UIMgr.getCurrentScene():addForm(uiPetRecruit);
            end

            local uiAirShipSkillExplain = UIAirShipSkillExplain.create(title, msg, getLocStr("more_slime"), callback);
            UIMgr.getCurrentScene():addForm(uiAirShipSkillExplain);
            AudioM.playFx("button_spell");
        end
    end
    btnExchange:addTouchEventListener(onExchangeClick);
    TextStyleM.setTextStyle(btnExchange, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnExchange:setTitleText(getLocStr("btn_text_more"));

    local btnActived = findChildByName(self.node, "BT/btn_actived");
    btnActived:setVisible(false);

end
